#!coding=utf-8
import threading

import time
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect

from Wechat.auth import WechatApi
from Wechat.models import wechat_user

wa = WechatApi(appid='wxc933621a5d3df147',appsecret='96f8a7e262868f2ecd510fc6b17330dc', token='jichong')
hw = WechatApi(appid='wxc933621a5d3df147',appsecret='96f8a7e262868f2ecd510fc6b17330dc', token='hardware')

mydeviceUrl = 'http://wxtest.mo-image.com/wechat/mydevice&response_type=code&scope=snsapi_userinfo&state=null'

def func():
    while (True):
        wa._access_token = None
        wa._jsapi_ticket = None
        try:
            print "Get New Token:", wa.access_token
            print "Get New JSAPI_TICKET", wa.jsapi_ticket
        except:
            pass;
        time.sleep(5000);

timer = threading.Timer(5000, func)
timer.start()

menuobj = {
    'button':[
        {
            'type': 'view',
            'name': '我的小智',
            'url': 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc933621a5d3df147&redirect_uri=%s#wechat_redirect' % mydeviceUrl
        },
        {
            'type': 'click',
            'name': '微信商城',
            'key': 'MENU_2_0_MALL'
        },
        {
            'name': '关于我们',
            'sub_button': [
                {
                    'type': 'view',
                    'name': '营养联盟',
                    'url': 'http://www.soso.com/'
                },
                {
                    'type': 'view',
                    'name': '代理加盟',
                    'url': 'http://v.qq.com/'
                },
                {
                    'type': 'click',
                    'name': '使用帮助',
                    'key': 'V1001_GOOD'
                }
            ]
        }
    ]
}


# Create your views here.
def hardware(request):
    if request.method == 'GET':
        print "enter hardware function"
        signature = request.GET.get('signature')
        timestamp = request.GET.get('timestamp')
        print "timestamp", timestamp;
        nonce     = request.GET.get('nonce')
        print "Got param"
        if hw.check_signature(signature, timestamp, nonce):
            print 'Accept'
            return HttpResponse(request.GET.get('echostr'))
        else:
            print 'Wrong'
            return HttpResponse(request.GET.get(''))


def connect(request):
    if request.method == 'GET':
        print "enter connect function"
        print "begin basic"
        signature = request.GET.get('signature')
        timestamp = request.GET.get('timestamp')
        print "timestamp", timestamp;
        nonce     = request.GET.get('nonce')
        print "Got param"
        if wa.check_signature(signature, timestamp, nonce):
            print 'Accept'
            return HttpResponse(request.REQUEST.get('echostr'))
        else:
            print 'Wrong'
            return HttpResponse(request.REQUEST.get(''))
    elif request.method == 'POST':

        print "enter POST function"
        print "begin basic"
        signature = request.POST.get('signature')
        timestamp = request.POST.get('timestamp')
        nonce     = request.POST.get('nonce')
        print "Got param"
        print "request.body", request.body
        wa.create_menu(menuobj)
        # if wechat.parse_data(request.body, msg_signature=signature, timestamp=timestamp, nonce=nonce):
        # try:
        #     wechat.parse_data(request.body);
        #     xml = wechat.response_text(content='欢迎欢迎')
        # except:
        #     print exceptions.ParseError

        return HttpResponse("")

def test(request):
    text = render(request, 'Wechat/test.html');
    return text

def test_add(request):
    text = render(request, 'Wechat/test_add.html');
    return text

def adddevice(request):
    wx_cfg = wa.calc_wx_config(request)
    print "wx_cfg", wx_cfg
    context={};
    context['wx_cfg'] = wx_cfg
    text = render(request, 'Wechat/adddevice.html', context);
    return text
	
def mydevice(request):
    context = {'title': '我的小智'}
    if request.method == 'GET':
        if 'openid' in request.session:
            print "openid in session", request.session['openid']
            openid = request.session['openid']
            print "got u",openid


        else:
            code = request.GET.get('code')
            if code:
                print "code:", code;
                token_data, error = wa.get_auth_access_token(code);
                print "auth finish data", token_data;
                if error:
                    print "鉴权失败"
                    return HttpResponse("鉴权失败")
                user_info, error = wa.get_user_info(token_data['access_token'], token_data['openid']);
                if error:
                    print "获取用户信息失败"
                    return HttpResponse("获取用户信息失败")
                # 用户对象存入session
                request.session['user'] = user_info['openid'];
                u = wechat_user()
                u.openid     = user_info['openid'];
                u.province   = user_info['province'];
                u.city       = user_info['city'];
                u.headimgurl = user_info['headimgurl'];
                u.language   = user_info['language'];
                u.sex        = user_info['sex'];
                u.nickname   = user_info['nickname'];
                request.session['openid'] = u.openid;
                request.session['auth_access_token'] = token_data['access_token'];
                u.save();

                print "userinfo", user_info

        #获得所有该用户绑定的设备信息
        print "session"
        print "session", request.session['openid']
        print "session", request.session['auth_access_token']
        bind_info, error = wa.get_bind_device(request.session['openid'])
        print "bind_info", bind_info;
        print "created menu"
        print "context", context;
        context['device_list'] = bind_info["device_list"];
        wx_cfg = wa.calc_wx_config(request)
        print "wx_cfg", wx_cfg
        context['wx_cfg'] = wx_cfg
        return render(request, 'Wechat/mydevice.html', context);

def devicestatus(request, device_type, device_id):
    wx_cfg = wa.calc_wx_config(request)
    print "wx_cfg", wx_cfg
    context={};
    context['wx_cfg'] = wx_cfg
    context['device_id'] = device_id
    context['device_type'] = device_type
    text = render(request, 'Wechat/devicestatus.html', context);
    return text;

def sendmessage(request, device_type, device_id, opcode):
    if 'openid' in request.session:
        print "openid in session", request.session['openid']
        openid = request.session['openid']
        print "got u", openid
        ret, error = wa.send_transmsg(device_type, device_id, openid, opcode);
    else:
        return HttpResponse("fail")
    return HttpResponse("ok")